import { createRouter, createWebHistory, type Router, type RouteRecordRaw } from "vue-router";
import publicRoutes from "./modules/publicRoutes";
import webRoutes from "./modules/webRoutes";
import { useTabsStore } from "@/store/modules/tabs";
import { treeTransferRoutes } from "./lib";

/**
 * @description: 路由方法
 * @return {*}
 */
const routerMethods = {
  /**
   * @description: 注册路由
   * @return {*}
   */
  createRouter: () => {
    return createRouter({
      history: createWebHistory(import.meta.env.BASE_URL),
      routes: [...publicRoutes]
    });
  },
  /**
   * @description: 替换路由表
   * @return {*}
   */
  resetRouter: (newRoutes: RouteRecordRaw[]) => {
    // 获取全部已注册的路由
    const routes = router.getRoutes();
    // 删除所有路由
    routes.forEach((route) => {
      if (!route.name) return;
      router.removeRoute(route.name);
    });
    // 添加新路由
    newRoutes.forEach((route) => {
      if (!route.name) return;
      router.addRoute(route);
    });
  },
  /**
   * @description: 路由处理
   * @return {*}
   */
  handleRoutes: () => {
    const children = treeTransferRoutes(webRoutes?.children || []);
    routerMethods.resetRouter([{ ...webRoutes, children }]);
  }
};
// 注册路由
const router = routerMethods.createRouter();
routerMethods.handleRoutes();
/**
 * @description: 替换原来的router.go方法
 * @return {*}
 */
const originalGo = router.go;
router.go = function (index: number) {
  useTabsStore().closeTab(this.currentRoute.value, "self");
  originalGo.call(this, index);
};

export { routerMethods };
export default router as Router;
